package wang.wangby.utils.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author ming
 * @date 2014年3月3日上午12:17:40
 */
public class ThreadPool{
	// 线程池
	private ThreadPoolExecutor threadPool;
	//超过线程池最大值,自己执行次数
	private AtomicLong rejected=new AtomicLong();

	public ThreadPool(int corePoolSize,int maximumPoolSize,int keepAliveTime,int queue){
		TimeUnit unit=TimeUnit.SECONDS;
		BlockingQueue<Runnable> workQueue=null;
		if(queue==0) {
			workQueue=new SynchronousQueue();
		}else {
			 workQueue=new ArrayBlockingQueue<Runnable>(queue);
		}
		
		threadPool=new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,noticeHandler);
	}
	
	public ThreadPool(int corePoolSize,int maximumPoolSize,int keepAliveTime,int queue,RejectedExecutionHandler rejectedHandler){
		TimeUnit unit=TimeUnit.SECONDS;
		BlockingQueue<Runnable> workQueue=null;
		if(queue==0) {
			workQueue=new SynchronousQueue();
		}else {
			 workQueue=new ArrayBlockingQueue<Runnable>(queue);
		}
		
		threadPool=new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,rejectedHandler);
	}
	

	public void execute(final Event event){
		threadPool.execute(new Runnable(){
			public void run(){
				event.runInThreadPool();
			}
		});
	}

	//失败了就自己执行
	private  RejectedExecutionHandler noticeHandler=new RejectedExecutionHandler(){
		public void rejectedExecution(Runnable run,ThreadPoolExecutor executor){
			rejected.incrementAndGet();
			run.run();
		}
	};

	/** 当前线程池执行情况 */
	public PoolInfo getInfo(){
		return new PoolInfo();
	}

	public class PoolInfo{
		public int getActiveCount(){
			return threadPool.getActiveCount();
		}

		//已经完成的个数
		public long getCompletedTaskCount(){
			return threadPool.getCompletedTaskCount();
		}

		//曾经最大线程池个数
		public int getLargestPoolSize(){
			return threadPool.getPoolSize();
		}

		public long getTaskCount(){
			return threadPool.getTaskCount();
		}

		//正在排队的个数
		public int getQueueSeize(){
			return threadPool.getQueue().size();
		}

		//线程池大小
		public int getPoolSize(){
			return threadPool.getPoolSize();
		}

		//被拒绝个数
		public long getRejected(){
			return rejected.get();
		}

	}
}
